<template>
  <view class="content">
    <tui-form ref="formRef" :show-message="false" :model="formData">
      <!-- 单位工程 -->
      <tui-form-item arrow labelWidth='180' asterisk label="单位工程" prop="unitProject" @click="popupShow=true">
        <tui-input padding="0" :borderBottom="false" :disabled='true' v-model="formData.unitProject"
          placeholder="请选择"></tui-input>
      </tui-form-item>
      <tui-bottom-popup :zIndex="1002" :height="600" :maskZIndex="1001" :show="popupShow" @close="popupShow=false">
        <tui-cascade-selection :defaultItemList='defaultItemList' height="200px" :itemList="itemList"
          @complete="complete"></tui-cascade-selection>
      </tui-bottom-popup>

      <!-- 分部工程 -->
      <tui-form-item arrow labelWidth='180' asterisk label="分部工程" prop="subsection" @click="popupShow2=true">
        <tui-input padding="0" :borderBottom="false" :disabled='true' v-model="formData.subsection"
          placeholder="请选择"></tui-input>
      </tui-form-item>
      <tui-bottom-popup :zIndex="1002" :height="600" :maskZIndex="1001" :show="popupShow2" @close="popupShow2=false">
        <tui-cascade-selection :defaultItemList='defaultItemList2' height="200px" :itemList="itemList2"
          @complete="complete2"></tui-cascade-selection>
      </tui-bottom-popup>
      <tui-form-item labelWidth='180' asterisk label="检验批编号" prop="lotCode">
        <tui-input padding="0" :borderBottom="false" v-model="formData.lotCode" placeholder="请输入"></tui-input>
      </tui-form-item>
      <tui-form-item labelWidth='180' asterisk label="检验批名称" prop="lotName">
        <tui-input padding="0" :borderBottom="false" v-model="formData.lotName" placeholder="请输入"></tui-input>
      </tui-form-item>
      <tui-form-item labelWidth='180' asterisk label="检验批容量" prop="lotQuantity">
        <tui-input padding="0" :borderBottom="false" v-model="formData.lotQuantity" placeholder="请输入"></tui-input>
      </tui-form-item>
      <tui-form-item labelWidth='180' asterisk label="检验批部位" prop="lotPart">
        <tui-input padding="0" :borderBottom="false" v-model="formData.lotPart" placeholder="请输入"></tui-input>
      </tui-form-item>
      <tui-form-item labelWidth='180' asterisk label="验收依据" prop="basicBy">
        <tui-input padding="0" :borderBottom="false" v-model="formData.basicBy" placeholder="请输入"></tui-input>
      </tui-form-item>
      <!-- 验收日期 -->
      <tui-form-item arrow labelWidth='180' asterisk label="验收日期" prop="checkDate" @click="openCalendar">
        <tui-input padding="0" :borderBottom="false" :disabled='true' v-model="formData.checkDate"
          placeholder="请选择"></tui-input>
      </tui-form-item>
      <tui-calendar ref="calendar" :initStartDate="initStartDate" :initEndDate="initEndDate" lunar isFixed :type="2"
        @change="changeCalendar"></tui-calendar>
      <tui-form-item labelWidth='180' asterisk label="主要内容" prop="lotDescription">
        <tui-input padding="0" :borderBottom="false" v-model="formData.lotDescription" placeholder="请输入"></tui-input>
      </tui-form-item>
      <!-- 上传附件 -->
      <tui-form-item labelWidth='180' asterisk label="上传图片" prop="files">
        <tui-upload :value='value' @getFileId='getFileId' :serverUrl="serverUrl" @complete="completeUpload"
          @remove="remove"></tui-upload>
      </tui-form-item>
      <view style="padding:0 10px 10px 10px;">
        <tui-form-button text="提交" @click="submit"></tui-form-button>
      </view>
    </tui-form>
  </view>
</template>

<script setup lang="ts">
  import { onLoad } from '@dcloudio/uni-app'
  import { ref, onMounted } from 'vue';
  import { deleteProjectLotFile2, updateProjectLotProcess, getFullProjectLotInfoById, reStartProjectLotProcess, startProjectLotProcess, addProjectLot, getProjectUnitProjectManageList, getSysSubsectionManageList } from '@/apis/lot.js';
  const popupShow = ref(false)
  const popupShow2 = ref(false)
  const itemList = ref([])
  const itemList2 = ref([])
  const formRef = ref(null);
  const calendar = ref(null);
  const serverUrl = 'http://192.168.1.127:8086/project-lot/uploadProjectLotAttach'
  const imageList = ref([])
  const pendingDeleteFiles = ref([])
  const value = ref([])
  const initEndDate = ref('')
  const initStartDate = ref('')
  const defaultItemList = ref([])
  const defaultItemList2 = ref([])

  const rules = [
    {
      name: "unitProject",
      rule: ["required"],
      msg: ["请选择单位工程"]
    }, {
      name: "subsection",
      rule: ["required"],
      msg: ["请选择分部工程"]
    }, {
      name: "lotCode",
      rule: ["required"],
      msg: ["请输入检验批编号"]
    }, {
      name: "lotQuantity",
      rule: ["required"],
      msg: ["请输入检验批容量"]
    }, {
      name: "lotPart",
      rule: ["required"],
      msg: ["请输入检验批部位"]
    }, {
      name: "basicBy",
      rule: ["required"],
      msg: ["请输入验收依据"]
    }, {
      name: "checkDate",
      rule: ["required"],
      msg: ["请选择验收日期"]
    }, {
      name: "lotDescription",
      rule: ["required"],
      msg: ["请输入主要内容"]
    }, {
      name: "lotName",
      rule: ["required"],
      msg: ["请输入检验批名称"]
    }];

  const formData = ref({
    basicBy: "",
    checkEndDate: "",
    checkStartDate: "",
    fileIds: [],
    lotCode: "",
    lotDescription: "",
    lotName: "",
    lotPart: "",
    lotQuantity: "",
    subAndUnitProjectIds: [],
    sysSubsectionIds: [],
    unitProject: '',
    subsection: '',
    checkDate: '',
    projectLotFileList:[]
  })

  const projectId = uni.getStorageSync('projectInfo').id
  const isEdit = ref(false)
  const lotid = ref(0)

  onMounted(() => {
    getList()
  });

  onLoad(({ lotId }) => {
    //   //如果有lotId就是编辑状态 再次提交时发起重新送审
    //   //添加一个状态判断编辑还是新增
    isEdit.value = false
    if (lotId) {
      lotid.value = lotId
      isEdit.value = true
      pendingDeleteFiles.value = []
      getFullProjectLotInfoById(lotId).then(res => {
        console.log(res.data.data);
        let data = res.data.data
        formData.value = data
        //回显单位工程和分部工程
        formData.value.unitProject = data.unitProjectName + '-' + data.subUnitProjectName
        formData.value.subAndUnitProjectIds = [data.unitProjectId, data.subUnitProjectId]


        formData.value.subsection = data.subsectionName + '-' + data.tenderSubsectionName + '-' + data.branchName
        formData.value.sysSubsectionIds = [data.subsectionId, data.tenderSubsectionId, data.branchId]
        setTimeout(() => {
          defaultItemList.value = [data.unitProjectName, data.subUnitProjectName]
          defaultItemList2.value = [data.subsectionName, data.tenderSubsectionName, data.branchName]
        }, 100)


        //回显验收日期
        initStartDate.value = data.checkStartDate
        initEndDate.value = data.checkEndDate
        formData.value.checkDate = data.checkStartDate + ' 至 ' + data.checkEndDate

        //回显照片
        value.value = data.projectLotFileList.map(e => 'http://' + e.filePath)
        formData.value.fileIds = data.projectLotFileList.map(e => e.id)
        console.log(formData.value.fileIds);
      })
    }
  })

  //单位工程
  const complete = (e) => {
    formData.value.unitProject = e.result.map(e => e.text).join('-')
    formData.value.subAndUnitProjectIds = e.result.map(e => e.value)
    popupShow.value = false
  }


  //分部工程
  const complete2 = (e) => {
    formData.value.subsection = e.result.map(e => e.text).join('-')
    formData.value.sysSubsectionIds = e.result.map(e => e.value)
    popupShow2.value = false
  }

  //验收日期
  const openCalendar = () => {
    calendar.value.show()
  }

  const changeCalendar = (e) => {
    formData.value.checkDate = e.startDate + ' 至 ' + e.endDate
    formData.value.checkStartDate = e.startDate
    formData.value.checkEndDate = e.endDate
  }

  //文件上传功能
  const completeUpload = (e) => {
    imageList.value = e.imgArr;
  }

  const remove = (e) => {
    pendingDeleteFiles.value.push(formData.value.fileIds[e.index])
    formData.value.fileIds.splice(e.index, 1)
  }

  const getFileId = (value) => {
    formData.value.fileIds.push(value.fileId);
  }

  //获取列表数据
  const getList = () => {
    getProjectUnitProjectManageList(projectId).then(res => {
      itemList.value = handleData(res.data.data);
    })
    getSysSubsectionManageList().then(res => {
      itemList2.value = handleData(res.data.data);
    })
  }

  //转换格式
  const handleData = (data) => {
    return data.map(item => ({
      text: item.nodeName,
      value: item.id,
      children: item.children ? handleData(item.children) : null
    }));
  }


  //提交表单
  const submit = async (values) => {
    console.log(formData.value);
    if (isEdit.value === false) {
      //新增
      if (formRef.value) {
        formRef.value.validate(formData.value, rules, true).then((res) => {
          if (res.isPass && formData.value.fileIds.length > 0) {
            addProjectLot(projectId, formData.value).then(res => {
              startProjectLotProcess(res.data.data).then(res => {
                if (res.data.code === 200) {
                  uni.navigateTo({
                    url: '/pages/lot/lot'
                  })
                  // plus.nativeUI.toast("新增成功");
                }
              })
            })
          } else {
            plus.nativeUI.toast("请上传图片");
          }
        })
      }
    } else {
      console.log(formData.value);

      //编辑
      if (formRef.value) {
        formRef.value.validate(formData.value, rules, true).then((res) => {
          if (res.isPass && formData.value.fileIds.length > 0) {
            // 删除已缓存的附件
            if (pendingDeleteFiles.value.length > 0) {
              deleteProjectLotFile2(pendingDeleteFiles.value).then(res => {
                console.log('删除成功');
              })
            }
            formData.value.projectLotFileList = formData.value.fileIds.map(e => ({ id: e }))
            updateProjectLotProcess(formData.value).then(res => {
              if (res.data.code === 200) {
                reStartProjectLotProcess(lotid.value).then(res => {
                  uni.navigateTo({
                    url: '/pages/lot/lot'
                  })
                  // plus.nativeUI.toast("重新送审成功");
                })
              }
            })
          }
        })
      }
    }
  }
</script>

<style lang="scss" scoped>
  .content {
    background-color: #fff;
    // padding: 0px 10px 10px 10px;
  }
</style>